from app import create_app
from flask import request, jsonify
from flask import render_template
from app.utils.common import Common
from app.model_train_predict.lstm_model_train import LSTMModelTrainPredict
# 导入Neo4jGraph
from app.spectrum.map_display import NeoGraph
from app.spectrum.neo4j_map import Neo4jMap

app = create_app()

@app.route('/')
def index():
    # 实例化对象
    # lstm_model = LSTMModelTrainPredict()
    # lstm_model.model_application("train")
    # common = Common()
    # datas, word2id = common.build_data()
    # print(datas)
    # print(word2id)
    # 展示静态页面(模板文件)
    return render_template("index.html")

@app.route("/graph")
def neo4j_graph():
    # 展示图谱页面
    return render_template("graph.html")

# 命名实体识别
@app.route("/lstm_crf_predict", methods=["POST"])
def lstm_crf_predict():
    # 1、实例化对象
    lstm_model_train_predict = LSTMModelTrainPredict()
    # 2、获取前端页面传递过来的参数
    text = request.get_json()
    # 3、模型预测
    result = lstm_model_train_predict.model_application("predict", text["text"])
    # 提取出键名和键值
    first_key = list(result.keys())[0] if result else "暂无"
    first_value = list(result.values())[0] if result else "暂无"
    # 将以上两个值进行组装
    result = {
        "text": first_key,
        "type": first_value
    }
    # 注意：返回json格式的数据
    return jsonify({"success": 200, "result": result, "text": text["text"]})

# 加载图谱数据
@app.route('/neo4j')
def neo4j():
    # 实例化NeoGraph对象
    neo_map = Neo4jMap()
    # 建立连接
    neo_map.neo4j_connect()
    nodes, edges, length = neo_map.get_visualization_data(1000)
    return jsonify({
        'nodes': nodes,
        'edges': edges,
        'count': len(nodes)
    })

# 获取所有spo关系
@app.route("/all")
def get_all_spo():
    # 实例化Neo4jMap对象
    neo_map = Neo4jMap()
    # 根据条件过滤SPO关系
    spo_list, count, timestamp = neo_map.get_all_spo()
    return jsonify({
        'count': count,
        'spo_list': spo_list,
        'timestamp': timestamp
    })

# 条件过滤
@app.route("/filter")
def get_filtered_spo():
    # 实例化Neo4jMap对象
    neo_map = Neo4jMap()
    # 根据条件过滤SPO关系
    start_label = request.args.get('start_label', '')
    rel_type = request.args.get('rel_type', '')
    end_label = request.args.get('end_label', '')
    search_term = request.args.get('search', '')
    count, spo_list, query, timestamp = neo_map.get_filtered_spo(start_label, rel_type, end_label, search_term)
    return jsonify({
        'count': count,
        'spo_list': spo_list,
        'query': query,
        'timestamp': timestamp
    })

# 获取数据库元数据
@app.route('/metadata')
def get_metadata():
    # 实例化Neo4jMap对象
    neo_map = Neo4jMap()
    # 获取元数据
    labels, relationship_types, node_count, relationship_count = neo_map.get_metadata()
    return jsonify({
        'labels': labels,
        'relationship_types': relationship_types,
        'node_count': node_count,
        'relationship_count': relationship_count
    })

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=6969, debug=True)
